<template>
  <div class="user">
    <el-form label-position="right" label-width="100px" :model="userFrom" style="max-width: 600px">
      <el-form-item label="头像" class="formItem">
        <img-upload style="width:100px;"
        v-model:picture="userFrom.avatar" />
      </el-form-item>
  
      <el-form-item label="账户" class="formItem">
        <el-input disabled readonly v-model="userFrom.userName" />
      </el-form-item>
      <el-form-item label="名称" class="formItem">
        <el-input v-model="userFrom.name" />
      </el-form-item>
      <el-form-item label="邮箱" class="formItem">
        <el-input v-model="userFrom.email" />
      </el-form-item>
      <el-form-item label="电话" class="formItem">
        <el-input v-model="userFrom.phone" />
      </el-form-item>
      <div class="bottom">
        <el-button type="primary" @click="userUpdate">修改</el-button>
        <el-button type="info" @click="addDialogVisible = true">新增地址</el-button>
      </div>
    </el-form>
    <el-divider />
    <div v-if="addressTable.length > 0" class="table">
      <!-- 表格展示 -->
      <el-table :data="addressTable" stripe style="width: 100%">
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="phone" label="收货电话" />
        <el-table-column prop="province" label="省" />
        <el-table-column prop="city" label="市" />
        <el-table-column prop="area" label="区" />
        <el-table-column prop="specific" label="具体地址" />
        <el-table-column prop="createTime" label="创建时间" width="190" />
        <el-table-column prop="updateTime" label="修改时间" width="190" />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="showUpdate(scope.row.id)">修改</el-button>
            <el-button link type="danger" size="small" @click="deleteData(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 空状态 -->
    <div v-if="addressTable.length <= 0">
      <el-empty description="暂无数据" />
    </div>
  </div>

  <!-- 新增地址弹出框 -->
  <el-dialog v-model="addDialogVisible" title="新增地址信息" width="40%">
    <div class="addForm">
    <el-form label-position="right" :model="addform">
      <el-form-item label="收货人" class="addFormItem">
        <el-input v-model="addform.name" placeholder="请输入收货人" clearable />
      </el-form-item>
      <el-form-item label="收货电话" class="addFormItem">
        <el-input v-model="addform.phone" placeholder="收货电话" clearable/>
      </el-form-item>
      <el-form-item label="行政区划" class="addFormItem">
        <el-cascader
          v-model="division"
          :options="divisionTree"
          :props="props"
          filterable
        />
      </el-form-item>
      <el-form-item label="详细地址" class="addFormItem">
        <el-input v-model="addform.specific" placeholder="详细地址" />
      </el-form-item>
    </el-form>
  </div>
  <template #footer>
    <el-button type="primary" @click="addressAdd">新增</el-button>
    <el-button type="info" @click="addDialogVisible = false">取消</el-button>
  </template>
  </el-dialog>

  <!-- 修改地址弹出框 -->
  <el-dialog v-model="updateDialogVisible" title="修改地址信息" width="40%">
    <div class="addForm">
    <el-form label-position="right" :model="updateForm">
      <el-form-item label="收货人" class="addFormItem">
        <el-input v-model="updateForm.name" placeholder="请输入收货人" clearable />
      </el-form-item>
      <el-form-item label="收货电话" class="addFormItem">
        <el-input v-model="updateForm.phone" placeholder="收货电话" clearable/>
      </el-form-item>
      <el-form-item label="行政区划" class="addFormItem">
        <el-cascader
          v-model="division"
          :options="divisionTree"
          :props="props"
          filterable
        />
      </el-form-item>
      <el-form-item label="详细地址" class="addFormItem">
        <el-input v-model="updateForm.specific" placeholder="详细地址" />
      </el-form-item>
    </el-form>
  </div>
  <template #footer>
    <el-button type="primary" @click="addressUpdate">修改</el-button>
    <el-button type="info" @click="updateDialogVisible = false">取消</el-button>
  </template>
  </el-dialog>
</template>

<script setup>
import {reactive, onMounted, ref} from 'vue';
// import permission from '@/utils/permission.js';
import ImgUpload from '@/components/ImgUpload.vue';
import {info, updateById} from '@/api/user.js';
import { ElLoading ,ElMessage, ElMessageBox} from 'element-plus'
import {useStore} from 'vuex';
import {list, addAddress, getById, update, deleteById} from "@/api/address.js"
import {getTreeData} from '@/utils/pca.js';

const store = useStore();
// 行政区划选择的数据
const division = ref([]);
// 新增弹框显示
const addDialogVisible = ref(false);
// 修改弹框显示
const updateDialogVisible = ref(false);
// 行政区划所有数据
const divisionTree = ref([])
// 用户表单
const userFrom = reactive({
  id: null,
  name: null,
  userName: null,
  avatar: null,
  pwd: null,
  email: null,
  phone: null,
  confirmPwd: null
})
// 新增表单
const addform = reactive({
  name: null,
  phone: null,
  province: null,
  city: null,
  area: null,
  specific: null,
})

// 修改表单
const updateForm = reactive({
  id: null,
  name: null,
  phone: null,
  province: null,
  city: null,
  area: null,
  specific: null,
})

// 地址列表
const addressTable = ref([])
// 二级弹框展开的事件
const props = {
  expandTrigger: 'hover',
}

onMounted(async ()=>{
  if(!store.state.user){
    ElMessage({
      type: "warning",
      message: "请先登录!"
    });
    window.location.href = "/"
  }else{
    divisionTree.value = getTreeData();

    // 获取当前登录用户的信息
    await getUserInfo();
    await listAddress();
  }

})

// 删除数据
const deleteData = async (id) => {

try {
  await ElMessageBox.confirm(
    '确定要删除地址吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  await deleteById(id);
  // 删除后，重新刷新列表
  await listAddress();
} catch (e) {
}
}

// 展示修改信息
const showUpdate = async (id) => {
  const response = await getById(id);
  const data = response.data.data;
  updateForm.id = data.id;
  updateForm.name = data.name;
  updateForm.phone = data.phone;
  updateForm.province = data.province;
  updateForm.city = data.city;
  updateForm.area = data.area;
  updateForm.specific = data.specific;

  // 设置级联选择框的数据
  division.value[0] = updateForm.province
  division.value[1] = updateForm.city
  division.value[2] = updateForm.area
  // 显示弹框
  updateDialogVisible.value = true;
}

// 修改数据
const addressUpdate = async () => {
  const loading = ElLoading.service({ fullscreen: true })
  try {
    updateForm.province = division.value[0];
    updateForm.city = division.value[1];
    updateForm.area = division.value[2]; 
    await update(updateForm);
    // 重新查询
    await listAddress();
  } finally {
    // 关闭弹框
    updateDialogVisible.value = false;
    // 清空表单数据
    claerUpdateForm();
    division.value = []
    // 停止加载
    loading.close();
  }
}

// 清空修改表单数据
const claerUpdateForm = ()=>{
  updateForm.id = null;
  updateForm.area = null;
  updateForm.city = null;
  updateForm.name = null;
  updateForm.phone = null;
  updateForm.province = null;
  updateForm.specific = null;
}

// 新增地址
const addressAdd = async()=>{
  console.log(division.value);
  addform.province = division.value[0];
  addform.city = division.value[1];
  addform.area = division.value[2];
  const loading = ElLoading.service({ fullscreen: true })
  await addAddress(addform);
  // 清空表单数据
  clearAddform();
  // 重新请求所有地址
  await listAddress();
  loading.close();
  division.value = [];
  addDialogVisible.value = false;
}


// 清空表单
const clearAddform = ()=>{
  addform.name = null;
  addform.phone = null;
  addform.province = null;
  addform.city = null;
  addform.area = null;
  addform.specific = null;
}

// 获取所有地址
const listAddress = async()=>{
  const response = await list()
  addressTable.value = response.data.data;
}


// 获取用户信息
const getUserInfo = async()=>{
  const response = await info();
  const data = response.data.data;
  userFrom.id = data.id;
  userFrom.userName = data.userName;
  userFrom.name = data.name;
  userFrom.userName = data.userName;
  userFrom.avatar = data.avatar;
  userFrom.pwd = data.pwd;
  userFrom.email = data.email;
  userFrom.phone = data.phone;
}

// 修改用户信息
const userUpdate = async()=>{
  const loading = ElLoading.service({ fullscreen: true })
  // 根据用户id修改
  await updateById(userFrom);
  // 修改信息
  store.dispatch('refreshUserInfo')
  // 修改地址
  loading.close();
}

</script>

<style scoped>
.groupBtn{
  text-align: center;
}
.user{
  margin-left: 100px;
}
.bottom{
  text-align: center;
}

.form {
  width: 100%;
  height: 100px;
}



.addForm {
  width: 300px;
  margin: auto;
}

.addFormItem {
  width: 300px;
}
.addForm {
  width: 300px;
  margin: auto;
}
</style>